package com.example.labapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedList;

public class mainMenu extends Activity {
    private Connection DBconn;
    private String stdID;
    private GridView gridMainMenu;
    private TextView txtSubtitle;
    private TextView txtAccessStatus;
    private LinkedList<menuItem> mData;
    private AlertDialog infDialog=null;
    private AlertDialog.Builder dialogBuild=null;
    private boolean AccessStatus;
    private void loadInf()
    {
        AlertDialog.Builder dlgBuilder=new AlertDialog.Builder(mainMenu.this);
        dlgBuilder.setTitle("处理中");
        dlgBuilder.setMessage("正在下载数据");
        dlgBuilder.setCancelable(false);  //点击空白处不返回
        infDialog=dlgBuilder.create();
        infDialog.show();
        AfterThread callbackAfer=(ErrorInf res)->{
            Looper.prepare();
            infDialog.cancel();
            if(!res.status)
            {
                AlertDialog.Builder dialogBuild=new AlertDialog.Builder(mainMenu.this);
                dlgBuilder.setTitle("错误");
                dlgBuilder.setMessage("数据下载失败\n"+res.errStr);
                dlgBuilder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        mainMenu.this.finish();
                    }
                });
                infDialog=null;
                infDialog=dlgBuilder.create();
                infDialog.show();
            }
            Looper.loop();
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                ErrorInf resData=new ErrorInf();
                try {
                    Class.forName("org.mariadb.jdbc.Driver");
                    DBconn = DriverManager.getConnection("jdbc:mariadb://124.222.159.110:3306/laboratory_APP?characterEncoding=utf-8/","labApp","3A9PvxE");
                    Statement statement1= DBconn.createStatement();
                    statement1.execute("INSERT INTO `laboratory_APP`.`appConnLog` (ConnInf) VALUES ('"+stdID+"');");
                    ResultSet res=statement1.executeQuery(String.format("SELECT ExamName,passGrade FROM appExams WHERE SubCollege IN (SELECT StdSubCollege FROM StudUser WHERE StdID=%s);",stdID));
                    res.next();
                    String exam=res.getString("ExamName");
                    int passGrade=res.getInt("passGrade");
                    res=statement1.executeQuery(String.format("SELECT %s FROM StudUser WHERE StdID=%s;",exam,stdID));
                    res.next();
                    if(res.getInt(exam)>passGrade)
                        AccessStatus=true;
                    else
                        AccessStatus=false;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(AccessStatus)
                                txtAccessStatus.setText("允许进入");
                            else
                                txtAccessStatus.setText("拒绝进入");
                        }
                    });
                } catch (SQLException | ClassNotFoundException throwables) {
                    throwables.printStackTrace();
                    resData.errStr=throwables.getMessage();
                    resData.errCode=1;
                    resData.status=false;
                    callbackAfer.callback(resData);
                    return;
                }
                resData.status=true;
                callbackAfer.callback(resData);
            }
        }).start();
    }

    private void commitSignin()
    {
        dialogBuild.setTitle("处理中");
        dialogBuild.setMessage("正在签到");
        dialogBuild.setCancelable(false);  //点击空白处不返回
        infDialog=dialogBuild.create();
        infDialog.show();
        AfterThread callbackAfer=(ErrorInf res)->{
            Looper.prepare();
            infDialog.cancel();
            if(res.status)
            {
                dialogBuild.setIcon(R.drawable.accds1);
                dialogBuild.setTitle("消息");
                dialogBuild.setMessage("签到成功");
                dialogBuild.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        infDialog.cancel();
                    }
                });
                infDialog=dialogBuild.create();
                infDialog.show();
            }
            else
            {
                dialogBuild.setTitle("错误");
                dialogBuild.setMessage("签到失败，请重试\n"+res.errStr);
                infDialog=dialogBuild.create();
                infDialog.show();
            }
            Looper.loop();
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                ErrorInf resData=new ErrorInf();
                try {
                    Statement stmt=DBconn.createStatement();
                    stmt.execute("INSERT INTO appSignIn (StdID) VALUES ("+stdID+");");
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                    resData.errStr=throwables.getMessage();
                    resData.status=false;
                    callbackAfer.callback(resData);
                    return;
                }
                resData.status=true;
                callbackAfer.callback(resData);
            }
        }).start();
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_menu_lay);
        dialogBuild=new AlertDialog.Builder(mainMenu.this);
        //从主窗口获取数据
        stdID=getIntent().getStringExtra("stdID");

        //创建组件映射
        txtAccessStatus=findViewById(R.id.gridMainAccessStatus);
        gridMainMenu=findViewById(R.id.gridMainMenu);
        txtSubtitle=findViewById(R.id.gridMainSubTitle);
        txtSubtitle.setText("欢迎使用,"+getIntent().getStringExtra("userName"));
        //获取数据
        loadInf();

        mData=new LinkedList<menuItem>();
        mData.add(new menuItem("考试",R.drawable.icon35));
        mData.add(new menuItem("签到",R.drawable.icon36));
        gridMainMenu.setAdapter(new menuAdapter(mData,mainMenu.this));
        gridMainMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch(i)
                {
                    case 0: //考试
                        Intent intent = new Intent(mainMenu.this,selectExamActivity.class);
                        intent.putExtra("stdID",stdID);
                        startActivity(intent);
                        break;
                    case 1:  //签到
                        commitSignin();
                }
            }
        });
    }
}
